<script setup>
import { ref } from 'vue'
import { useUserStore } from '@/store/user';
import useEmo from '../../../hooks/useEmo';
import V3Emoji from "vue3-emoji";
import "vue3-emoji/dist/style.css"
import { submitCommentApi } from '../../../apis/comment';
import { useRoute } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getAllAttentionListApi } from '@/apis/mention'


const data = defineProps({
  getCommentList: {
    type: Function,
    required: true,
  },
  getPostDetail: {
    type: Function,
    required: true,
  },
  currentPage: {
    type: Number,
  }

})

const useStore = useUserStore()
const route = useRoute()

const { onVue3Emoje, optionsName, content } = useEmo()


// #region 上传图片相关

// 上传图片的列表
const fileList = ref([])

//删除方法
const handleRemove = (file) => {

  const index = fileList.value.indexOf(file);
  if (index !== -1) {
    fileList.value.splice(index, 1);
  }

  //调用删除图片的接口，直接去数据库将这个url删掉即可
}


// 上传图片成功的方法
const handleSuccess = (res, file, fileList) => {
  console.log(res);

  //成功方法会把展示的file数据和后台返回的数据都拿到
  file.url = res.data
  try {
    fileList.value.push(file)

  } catch (error) {
    // console.log(error)
  }
}

//上传图片时的检查
const handleBeforeUpload = (file) => {
  if (file.type !== 'image/gif' && file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png') {
    ElMessage.error('请上传jpg/jpeg/png/gif格式图片!')
    return false
  } else if (file.size / 1024 / 1024 > 3) {
    ElMessage.error('图片超过3MB!')
    return false
  }

}

// #endregion


// #region 回复框，提及组件
const options = ref([])


// #endregion


// #region 提交回复的逻辑
const handleSubmit = async () => {

  // 获得图片列表
  const imgList = fileList.value.map(item => item.url)

  // 判断图片不能为空
  if (content.value.trim() === '') {
    ElMessage.error('内容不能为空!')
    return
  }

  // 发送请求
  const res = await submitCommentApi({
    userId: useStore.userInfo.id,
    content: content.value,
    postId: route.params.id,
    imgList
  })

  content.value = ''

  fileList.value = []

  //再次发送请求获取评论列表
  data.getCommentList(undefined, sessionStorage.getItem('currentPage'))

  //再次发送请求获得帖子详情
  data.getPostDetail()

  // 再次获得经验值
  useStore.getExperience()

  ElMessage({
    type: 'success',
    message: res.data,
    duration: 2 * 1000,
  })
}

// #endregion


// #region 监听回车键，shift 加 enter换行
const handleKeydown = (event) => {
  // console.log(event.key);

  // 检测是否按下了Enter键
  if (event.key === 'Enter') {
    // 如果同时按下了Shift键，则不处理，允许换行
    if (event.shiftKey) {
      return; // 不做任何处理，允许换行
    } else {
      if (isMention.value) {
        /* 进来这里就是说明用户用了提及，要阻止提交评论的方法 */
        /* 将isMention设置为false，下次再按enter键时，才会触发提交评论的方法 */
        isMention.value = false;
      } else {
        event.preventDefault(); // 阻止默认的换行行为
        handleSubmit(); // 提交评论
      }

    }
  }
}

// #endregion

//#region 提及组件代码
const isMention = ref(false)
const handleSearch = async () => {
  isMention.value = true;

  /* 获得当前用户所有的关注列表 */
  const res = await getAllAttentionListApi(useStore.userInfo.id)
  options.value = res.data
}

// #endregion



</script>

<template>
  <div class="reply">
    <span class="title">发表回复</span>

    <div class="image">


      <el-upload action="/api/common/upload" :headers="{ token: useStore.token }" name="file" list-type="picture-card"
        :auto-upload="true" :before-upload="handleBeforeUpload" :on-success="handleSuccess" v-model:file-list="fileList"
        :data="{ type: 'reply' }" :limit="5">
        <svg-icon name="tupian"></svg-icon>

        <template #file="{ file }">
          <div>
            <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
            <span class="el-upload-list__item-actions">


              <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
                <el-icon>
                  <Delete />
                </el-icon>
              </span>
            </span>
          </div>
        </template>


      </el-upload>
      <div class="limit">
        <span>{{ fileList.length }} / 5</span>
      </div>

      <!-- 表情包组件 -->
      <V3Emoji v-model="comment" :options-name="optionsName" :textArea="true" class="emoji" @click-emoji="onVue3Emoje"
        :recent="true" size="big" fixPos='top'>
      </V3Emoji>

    </div>

    <!-- 提及组件 -->
    <div class="mention">
      <el-mention v-model="content" resize="none" type="textarea" :options="options" :rows="7" style="font-size: 20px;"
        placeholder="可以用@来提及你的关注哦，快来试试吧！" @keydown="handleKeydown" @search="handleSearch">

        <template #label="{ item }">
          <div style="display: flex; align-items: center">
            <el-avatar :size="24" :src="item.avatar" />
            <span style="margin-left: 6px">{{ item.label }}</span>
          </div>
        </template>

      </el-mention>
      <el-button @click="handleSubmit" type="primary" class="published">发表</el-button>
    </div>
  </div>
</template>

<style lang='scss' scoped>
.reply {
  width: 100%;
  border: 2px solid rgb(232, 225, 225);

  padding: 30px;

  .image {
    display: flex;
    align-items: center;

    // 上传图片的样式   点击框的样式 
    ::v-deep .el-upload--picture-card {
      width: 50px;
      height: 50px;
      line-height: 50px;
      border: none;
    }

    //上传图片的样式     图片的样式
    ::v-deep .el-upload-list--picture-card .el-upload-list__item {
      width: 50px !important;
      height: 50px !important;
    }

    .emoji {
      // border: 1px solid red;
      margin-left: 10px;
      width: 30px;
      margin-bottom: 8px;


    }



  }

  .title {
    display: block;
    margin-bottom: 30px;
    font-size: 20px;
    font-weight: bold;
  }

  //todo:改变鼠标颜色
  .mention {
    font-size: 20px;

    &:hover {
      cursor: pointer;
      /* 自定义鼠标指针 */
    }
  }

  .published {
    margin-left: 1030px;
    margin-top: 15px;

  }
}
</style>